﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;

namespace SearchRS
{
    public class SratimSearcher : RSSearcher
    {
        private readonly string m_searchOrder;

        public SratimSearcher(string searchOrder)
        {
            m_searchOrder = searchOrder;
        }

        public TorecResults Search(string sratimLink)
        {
            TorecResults results = new TorecResults();

            ServicePointManager.Expect100Continue = false;
            Stream st = null;

            int tries = 0;
            WebResponse resp = null;
            while (tries < 20)
            {
                WebRequest req = NetworkServices.NetworkServices.SendGetRequest(sratimLink,
                                                               "",//"Accept-Encoding: gzip, deflate", 
                                                               "",//"Cookie: JSSESSIONID=81Q21PS0180NQ9T10G339205M3.O1110O; ym_pop_freq_expiration491640=Wed, 2 Sep 2009 17:45:12 UTC; ym_pop_freq491640=1; __utma=256733838.608426651.1251827109.1251827109.1251827109.1; __utmb=256733838; __utmc=256733838; __utmz=256733838.1251827109.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)",
                                                               "www.sratim.co.il",
                                                               true);
                try
                {
                    resp = req.GetResponse();
                    st = resp.GetResponseStream();
                    break;
                }
                catch (WebException)
                {
                    tries++;
                    Thread.Sleep(10000);
                }
            }

            // number of retires exceeded
            if (st == null)
                return results;

            StreamReader sr = new StreamReader(st);
            string buffer = sr.ReadToEnd();

            //MatchCollection matches = Regex.Matches(buffer, "כתוביות בעברית</div>.+?(<a href=\"([^\"]+)\">.+?title=\"([^\"]+)\".*)+", RegexOptions.Singleline);
            Dictionary<string, string> versions = new Dictionary<string, string>();
            //href="
            MatchCollection matches = Regex.Matches(buffer, "<a href=\"(downloadsubtitle.php\\?id\\=[^\"]+)\".+?class=\"subtitle_title\".+?title=\"([^\"]+)\"", RegexOptions.Singleline);
            string dummy;
            foreach (Match m in matches)
            {
                if (!versions.TryGetValue(m.Groups[2].Value, out dummy))
                    versions.Add(m.Groups[2].Value, m.Groups[1].Value);
            }

            string[] patterns = m_searchOrder.Split('|');
            List<List<string>> candidates = new List<List<string>>(patterns.Length);
            for (int i = 0; i < patterns.Length; i++) candidates.Add(new List<string>());

            foreach (string version in versions.Keys)
            {
                for (int i = 0; i < patterns.Length; i++)
                {
                    string theVersion = version.Replace("\n", "");
                    if (theVersion.ToLower().Contains(patterns[i].ToLower()))
                    {
                        if (candidates[i] == null) candidates[i] = new List<string>();
                        candidates[i].Add(theVersion);
                        break;
                    }
                }
            }

            for (int i = 0; i < candidates.Count; i++)
            {
                for (int j = 0; j < candidates[i].Count; j++)
                {
                    string chosen = candidates[i][j];
                    chosen = CleanName(chosen);
                    string subsLink = "http://sratim.co.il/" + versions[candidates[i][j]]; // GetSubsLink("http://sratim.co.il" + versions[candidates[i][j]]);
                    results.AddResult(chosen, subsLink);
                }
            }

            return results;

        }

        private string GetSubsLink(string originalSubsLink)
        {
            WebResponse resp;
            Stream st;
            string buffer = "";
            int tries = 10;

            while (buffer.IndexOf(".zip") == -1 && tries > 0)
            {

                WebRequest req = NetworkServices.NetworkServices.SendGetRequest(originalSubsLink,
                                                                                "Accept-Encoding: identity",
                                                                                "Cookie: __utma=232448605.623072534.1259694788.1259694788.1259694788.1; __utmz=232448605.1259694789.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmc=232448605",
                                                                                "",//Referer: http://www.sratim.co.il",
                                                                                true);
                try
                {
                    resp = req.GetResponse();
                    st = resp.GetResponseStream();
                }
                catch (WebException)
                {
                    return "";
                }

                StreamReader sr = new StreamReader(st);

                buffer = sr.ReadToEnd();
                tries--;
            }

            if (tries == 0)
                return "";

            int pos = buffer.IndexOf(".zip");
            int pos2 = buffer.LastIndexOf("/", pos);
            string subsLink = "torec.net/zip_versions/" + buffer.Substring(pos2 , pos - pos2  + 4);
            subsLink = "http://" + subsLink.Replace("//", "/");
            return subsLink;
        }

        private static string CleanName(string name)
        {
            int pos = name.IndexOf(".heb", StringComparison.InvariantCultureIgnoreCase);
            if (pos >= 0)
                name = name.Substring(0, pos);

            return name.Replace("-", " ").Replace(".", " ").Replace("[", " ").Replace("]", " ").Replace("\n", "");
        }


    }

}
